﻿using libedi.API;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO.Compression;
using Newtonsoft;
using Newtonsoft.Json;

namespace CodeBackup.Code
{
    public class Backup
    {


        private List<Database> databases;
        WebApi api = new WebApi(libedi.SourceType.CODE);

        string temp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempc"); 
        string FileName = string.Empty;
        public Backup(List<Database> databases, string FileName)
        {
            this.databases = databases;
            this.FileName = FileName;
        }
        public bool run()
        {
            if(databases == null)
            {
                return false;
            }
        
            if(Directory.Exists(temp))
            {
                Directory.Delete(temp, true);
            }
            Directory.CreateDirectory(temp);

            foreach(Database db in databases)
            {
                DataTable values = api.GetDataObject<DataTable>($"SELECT * FROM {db.baseName}");
                File.WriteAllText(Path.Combine(temp, $"{db.baseName}.txt") , JsonConvert.SerializeObject(values) );
            }



            ZipFile.CreateFromDirectory(temp,Path.Combine(ini.SaveDirec, FileName) );
            return true;
                
        }
    }
}
